# -*- coding: utf-8 -*-
#from correct_rotation_for_angle import process_images
import pythoncom
import wx
import wx.richtext
import wx.xrc
from PIL import Image
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import time
import os
from io import BytesIO
import sys
import subprocess
from pathlib import Path as pathdir
from win32com.client import Dispatch
import psutil
import zipfile
import requests
import base64
import re
import configparser
import threading
import xlrd
from xlutils.copy import copy as copywook
from concurrent.futures import ThreadPoolExecutor,wait as waitwith
from concurrent.futures import ALL_COMPLETED,FIRST_COMPLETED,FIRST_EXCEPTION
import winreg

import fateadm_api

#win32security.SetThreadToken(Thread, Token)

def getwring():
    try:
        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r"Software\Google\Chrome\BLBeacon")
            path = winreg.QueryValueEx(key,"version")
            return {"vis":True,"vlaue":path[0]}
        except FileNotFoundError:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r"SYSTEM\CurrentControlSet\Services\GoogleChromeElevationService")
            path = winreg.QueryValueEx(key,"ImagePath")
            return {"vis":False,"vlaue":path[0].split("Application")[0] + "Application"}
    except:
        return False


def logeer(m,s=None):
    if s:
        str_ = time.strftime("%Y-%m-%d %H:%M:%S") + " 这个错误被忽略了,这个错误可能会有影响 " + m + "\n"
    else:
        str_ = time.strftime("%Y-%m-%d %H:%M:%S") + m + "\n"
    with open("错误日志.log",'a',encoding='utf-8') as m:
        m.write(str_)


class setconfig():
    def __init__(self):
        self.con = configparser.ConfigParser()
        if os.path.exists("config.ini"):
            self.con.read(os.path.join('config.ini'), encoding='utf-8')
            setting.chromedriver = self.con.get("db", "chromedriver")
            setting.version = self.con.get("db", "version")
            setting.runsum = int(self.con.get("db", "runsum"))
            setting.rundef = int(self.con.get("db", "rundef"))
            setting.identify = int(self.con.get("db", "identify"))
            setting.window = int(self.con.get("db", "window"))
        else:
            self.con.add_section("db")
            self.set_cfg("db", "chromedriver", setting.chromedriver)
            self.set_cfg("db", "version", setting.version)
            self.set_cfg("db", "runsum", str(setting.runsum))
            self.set_cfg("db", "rundef", str(setting.rundef))
            self.set_cfg("db", "identify", str(setting.identify))
            self.set_cfg("db", "window", str(setting.window))

    def set_cfg(self, Affet, Buoote, CvHsdda):
        self.con.set(Affet, Buoote, str(CvHsdda))
        TscvgLop = open('config.ini', 'w', encoding='utf-8')
        self.con.write(TscvgLop)
        TscvgLop.close()


class setting:
    chromedriver = None
    version = None
    runsum = 1
    rundef = 0
    window = 0
    identify = 0
    work = None
    worb = None


class workbok(threading.Thread):
    def __init__(self,window,name):
        threading.Thread.__init__(self)
        self.window = window
        workbook = xlrd.open_workbook(name)
        self.table = workbook.sheet_by_name("Sheet1")
        self.user = {}
        if self.window.m_choice3.Selection:
            setting.worb = copywook(workbook)
        else:
            setting.work = copywook(workbook)
        for um in range(0,self.table.nrows):
            if "账号" in self.table.row_values(um)[0]:
                continue
            self.user.update({self.table.row_values(um)[0]:{"name":self.table.row_values(um)[0],"old":self.table.row_values(um)[1],"new":self.table.row_values(um)[2],"x":um}})
        print(self.user)

    def start_run(self,pam):
        if self.window.m_choice3.Selection:
            baidu = baidulogin(pam["x"],pam["name"],pam["old"])
            try:
                wx.CallAfter(self.window.LogMessase,pam["name"] + " 开始工作")
                baidu.login()
            except Exception as e:
                logeer(str(e)+" 如果有此错误记录将说明网页有所变动,需要修改程序")
                baidu.driver.quit()
        else:
            thstrart = WorkerThread(self.window,pam["x"],pam["name"],pam["old"],pam["new"])
            try:
                wx.CallAfter(self.window.LogMessase,pam["name"] + " 开始工作")
                thstrart.login(False)
            except Exception as e:
                logeer(str(e)+" 如果有此错误记录将说明网页有所变动,需要修改程序")
                thstrart.driver.quit()
                wx.CallAfter(self.window.LogMessase," 如果有此消息将说明网页有所变动")

    def run(self):
        self.window.m_button9.Enable(True)
        if not setting.rundef:
            WorkerThream(self.window,self.user[list(self.user)[0]]).start()
        else:
            with ThreadPoolExecutor(max_workers=setting.runsum+2) as ex:
                lisrrun = []
                for use in self.user:
                    lisrrun.append(use)
                    if len(lisrrun) == setting.runsum+2 or self.user[use]['x'] == self.table.nrows-1:
                        for res in [ex.submit(self.start_run,self.user[page]) for page in lisrrun]:
                            res.result()
                        lisrrun = []
            ex.shutdown(wait=True)


class WorkerThread(object):
    def __init__(self,windows,diy,user,password,newpassword):
        self.diy = diy
        self.user = user
        self.password = password
        self.newpassword = newpassword
        self.window = windows
        option=webdriver.ChromeOptions()
        if setting.window:
            option.add_argument('headless')
        self.driver = webdriver.Chrome(executable_path=setting.chromedriver,chrome_options=option)

    def WebDir(self,ysu,xpath,times):
        try:
            WebDriverWait(self.driver,times).until(EC.visibility_of_element_located((ysu,xpath)))
            return True
        except:
            return False

    def image_str(self,idclass):
        png64 = self.driver.get_screenshot_as_base64()
        png64 = base64.b64decode(png64)
        page_snap_obj = Image.open(BytesIO(png64))
        img = self.driver.find_element_by_css_selector(idclass)
        imgxy = img.location
        right = imgxy['x'] + img.size['width']
        bottom = imgxy['y'] + img.size['height']
        image_obj = page_snap_obj.crop((imgxy['x'], imgxy['y'], right, bottom))
        if not os.path.exists("files"):
            os.mkdir("files")
        file = "files" + "\\" + str(time.time()).replace(".","") + ".png"
        image_obj.save(file)
        return file

    def booksave(self):
        try:
            setting.work.save("百度改密.xls")
            wx.CallAfter(self.window.LogMessase,self.user+" 保存成功")
        except PermissionError:
            logeer("表格被其他程序占用,保存失败")
            wx.CallAfter(self.window.LogMessase,self.user+" 表格被其他程序占用,保存失败")
        except Exception as e:
            logeer(str(e))
            wx.CallAfter(self.window.LogMessase,self.user+" 保存失败")
        self.driver.quit()

    def login(self,callback):
        if not callback:
            self.url = 'https://cas.baidu.com/?tpl=www2'
            self.driver.get(self.url)
        self.WebDir(By.XPATH, '//*[@id="app"]/div[1]/div[2]/div[2]/div[1]/span',60)
        textlogon = self.driver.find_element_by_xpath('//*[@id="app"]/div[1]/div[2]/div[2]/div[1]/span').text
        if textlogon == "账号登录":
            self.driver.find_element_by_xpath('//*[@id="app"]/div[1]/div[2]/div[2]/div[1]/span').click()
            time.sleep(0.5)
        self.WebDir(By.XPATH,'//*[@id="uc-common-account"]',30)
        self.driver.find_element_by_xpath('//*[@id="uc-common-account"]').send_keys(self.user)
        self.driver.find_element_by_xpath('//*[@id="ucsl-password-edit"]').send_keys(self.password)
        self.driver.find_element_by_xpath('//*[@id="submit-form"]').click()
        wx.CallAfter(self.window.LogMessase,self.user+" 登录")
        def tongying(m):
            wx.CallAfter(self.window.LogMessase,self.user+" 同意政策")
            xpath1 = '/html/body/div[{}]/div/div[2]/div/div[2]/div[2]/label/span[1]/input'.format(m)
            xpath2 = '/html/body/div[{}]/div/div[2]/div/div[2]/div[3]/button/span'.format(m)
            try:
                self.driver.find_element_by_xpath(xpath1).click()
                time.sleep(1)
                self.driver.find_element_by_xpath(xpath2).click()
                return True
            except NoSuchElementException:
                if m == 3:
                    return False
                return tongying(3)
            except Exception as e:
                logeer(str(e),s=True)
                return False
        returns = 0
        while True:
            if self.WebDir(By.XPATH, '//*[text()="百度推广政策简报公告"]',1):
                tongying(4)
            elif self.WebDir(By.XPATH, '//*[text()="APP应用下载页内容合规协议"]',1):
                tongying(4)
            elif self.WebDir(By.XPATH, '//*[text()="账户中心"]',1):
                time.sleep(1)
                if self.WebDir(By.XPATH, '//*[text()="百度推广政策简报公告"]',2):
                    tongying(4)
                elif self.WebDir(By.XPATH, '//*[text()="APP应用下载页内容合规协议"]',2):
                    tongying(4)
                else:
                    if not callback:
                        self.setpassword()
                    return ""
            elif self.WebDir(By.XPATH,'//*[text()="修改密码"]',1):
                self.netpassword()
                return ""
            elif self.WebDir(By.XPATH,'//*[@id="token-img"]',1):
                self.driver.maximize_window() # 窗口最大化准备截图
                self.driver.find_element_by_xpath('//*[@id="token-img"]').click()
                time.sleep(0.5)
                pngname = self.image_str('#token-img')
                if setting.identify == 0:
                    pngname = fateadm_api.TestFunc(pngname)
                else:
                    pngname = fateadm_api.baiduapi(pngname)
                self.driver.find_element_by_id("uc-common-token").send_keys(pngname)
                self.driver.find_element_by_id("submit-form").click()
            elif self.WebDir(By.XPATH,'//*[text()="拖动滑块，使图片角度为正"]',1):
                self.driver.maximize_window() # 窗口最大化准备截图
                time.sleep(0.5)
                wx.CallAfter(self.window.LogMessase,self.user+" 准备滑块纠正")
                pngname = self.image_str('.vcode-spin-img')
                #img_url = self.driver.find_element_by_xpath('//*[@class="vcode-spin-img"]').get_attribute("src")
                getcmd = subprocess.check_output("correct_rotation.exe {}".format(pngname))
                getcmd = re.sub("[\n\r]","",getcmd.decode("gbk"))
                movex = int(int(getcmd)/360*210)
                #print(img_url)
                elenment = self.driver.find_element_by_xpath('//*[@class="vcode-spin-button"]/p')
                ActionChains(self.driver).move_to_element(elenment).perform()
                drawing = ActionChains(self.driver).click_and_hold(elenment).move_by_offset(movex, 0).release()
                drawing.perform()
                
                #'//*[@class="vcode-spin-img"]'
            elif self.WebDir(By.XPATH,'//*[text()="用户名密码错误"]',1):
                #self.driver.find_element_by_xpath('//*[@id="submit-form"]').click()
                wx.CallAfter(self.window.LogMessase,self.user+" 密码错误")
                setting.work.get_sheet(0).write(self.diy, 5, "登录失败(用户名密码错误)")
                setting.work.get_sheet(0).write(self.diy, 6, time.strftime("%Y-%m-%d %H:%M:%S"))
                self.booksave()
                return ""
            else:
                wx.CallAfter(self.window.LogMessase,self.user+" 暂找不到页面")
                returns += 1
                if returns > 8:
                    wx.CallAfter(self.window.LogMessase,self.user+" 登录失败,即将进行下一个账号")
                    setting.work.get_sheet(0).write(self.diy, 5, "登录失败(未识别到页面)")
                    self.booksave()
                    return ""

    def netpassword(self):
        self.driver.find_element_by_xpath('//*[@id="OldPassword"]').send_keys(self.password)
        self.driver.find_element_by_xpath('//*[@id="NewPassword"]').send_keys(self.newpassword)
        self.driver.find_element_by_xpath('//*[@id="ReNewPassword"]').send_keys(self.newpassword)
        self.driver.find_element_by_xpath('//*[@id="Main"]/div[6]/input').click()
        if self.WebDir(By.XPATH,'//*[text()="重新登陆！"]',60):
            setting.work.get_sheet(0).write(self.diy, 5, "修改成功")
            setting.work.get_sheet(0).write(self.diy, 6, time.strftime("%Y-%m-%d %H:%M:%S"))
            self.driver.find_element_by_xpath('/html/body/div[1]/div[2]/table/tbody/tr/td/table/tbody/tr/td[1]/a').click()
            if self.WebDir(By.XPATH, '//*[@id="app"]/div[1]/div[2]/div[2]/div[1]/span',60):
                self.login(True)
                self.Binduser()
            else:
                setting.work.get_sheet(0).write(self.diy, 4, "未重新登录获取绑定")
        else:
            setting.work.get_sheet(0).write(self.diy, 5, "修改失败")
            setting.work.get_sheet(0).write(self.diy, 4, "未重新登录获取绑定")
        self.booksave()

    def Binduser(self):
        self.driver.find_element_by_xpath('//*[text()="账户中心"]').click()
        wx.CallAfter(self.window.LogMessase,self.user+" 点击账户中心")
        handl=self.driver.window_handles
        self.driver.switch_to.window(handl[-1])
        self.WebDir(By.XPATH, '//*[text()="账户管理"]',60)
        if self.WebDir(By.XPATH,'//*[@id="binding-abstract-mcc"]/div[1]/em/a',30):
            txt = self.driver.find_element_by_xpath('//*[@id="binding-abstract-mcc"]/div[1]/em/a').text
            if txt == "1":
                self.driver.find_element_by_xpath('//*[@id="binding-abstract-mcc"]/div[1]/em/a').click()
                self.WebDir(By.XPATH, '//*[text()="处理请求"]',60)
                self.driver.find_element_by_xpath('//*[text()="处理请求"]').click()
                self.WebDir(By.XPATH, '//*[text()="重要提醒："]',60)
                self.driver.find_element_by_xpath('//*[@id="binding-mcc-agreecheckbox"]').click()
                time.sleep(0.5)
                self.WebDir(By.XPATH, '//*[text()="同意绑定"]',60)
                self.driver.find_element_by_xpath('//*[text()="同意绑定"]').click()
                wx.CallAfter(self.window.LogMessase,self.user+" 同意绑定")
                self.WebDir(By.XPATH, '//*[text()="您已成功处理该绑定请求"]',60)
                self.driver.find_element_by_xpath('//*[text()="确定"]').click()
                setting.work.get_sheet(0).write(self.diy, 4, "有绑定信息")
                time.sleep(0.5)
            else:
                setting.work.get_sheet(0).write(self.diy, 4, "无绑定信息")
        else:
            setting.work.get_sheet(0).write(self.diy, 4, "未获取到绑定信息")

    def setpassword(self):
        self.Binduser()
        elenment = self.driver.find_element_by_xpath('//*[text()="账户管理"]')
        ActionChains(self.driver).move_to_element(elenment).perform()
        self.update_action('//*[text()="安全中心"]',elenment)
        wx.CallAfter(self.window.LogMessase,self.user+" 打开安全中心")
        handl=self.driver.window_handles
        self.driver.switch_to.window(handl[-1])
        self.WebDir(By.XPATH, '//*[text()="管理密码"]',60)
        elenment = self.driver.find_element_by_xpath('//*[text()="找回、修改密码从这里开始"]')
        ActionChains(self.driver).move_to_element(elenment).perform()
        self.update_action('//*[text()="修改密码"]',elenment)
        wx.CallAfter(self.window.LogMessase,self.user+" 打开修改密码页面")
        handl=self.driver.window_handles
        self.driver.switch_to.window(handl[-1])
        self.WebDir(By.XPATH, '//*[text()="登录密码修改"]',60)
        self.driver.find_element_by_xpath('//*[text()="登录密码修改"]').click()
        self.driver.find_element_by_xpath('//*[@id="old-password"]').send_keys(self.password)
        self.driver.find_element_by_xpath('//*[@id="new-password"]').send_keys(self.newpassword)
        self.driver.find_element_by_xpath('//*[@id="second-new-password"]').send_keys(self.newpassword)
        self.driver.find_element_by_xpath('//*[@id="modify-password-button"]').click()
        wx.CallAfter(self.window.LogMessase,self.user+" 修改密码")
        if self.WebDir(By.XPATH,'//*[text()="安全等级"]',60):
            setting.work.get_sheet(0).write(self.diy, 5, "修改成功")
            setting.work.get_sheet(0).write(self.diy, 6, time.strftime("%Y-%m-%d %H:%M:%S"))
        else:
            setting.work.get_sheet(0).write(self.diy, 5, "修改失败")
            setting.work.get_sheet(0).write(self.diy, 6, time.strftime("%Y-%m-%d %H:%M:%S"))
        self.booksave()

    def update_action(self,xpath_,elenment):
        while True:
            try:
                self.WebDir(By.XPATH, xpath_,2)
                self.driver.find_element_by_xpath(xpath_).click()
                break
            except Exception as e:
                logeer(str(e),s=True)
                ActionChains(self.driver).move_to_element(elenment).perform()


class baidulogin(object):
    def __init__(self,diy,user,password):
        option=webdriver.ChromeOptions()
        if setting.window:
            option.add_argument('headless')
        self.driver = webdriver.Chrome(executable_path=setting.chromedriver,chrome_options=option)
        self.url = "https://passport.baidu.com/v2/?login"
        self.diy = diy
        self.user = user
        self.password = password

    def login(self):
        self.driver.get(self.url)
        self.WebDir(By.XPATH,'//*[@class="login-form"]',60)
        namelogin = self.driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_3__qrcode"]/p[1]').text
        if namelogin == "扫码登录":
            self.driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_3__footerULoginBtn"]').click()
        self.WebDir(By.XPATH,'//*[@id="TANGRAM__PSP_3__userName"]',10)
        self.driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_3__userName"]').send_keys(self.user)
        self.driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_3__password"]').send_keys(self.password)
        self.driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_3__submit"]').click()
        timesum = 0
        while timesum<36:
            if self.WebDir(By.XPATH,'//*[text()="帐号管理"]',1):
                setting.worb.get_sheet(0).write(self.diy, 4, "登录成功")
                break
            elif self.WebDir(By.XPATH,'//*[@id="TANGRAM__PSP_3__errorWrapper"]//*[text()="用户名或密码有误，请重新输入或"]',1):
                setting.worb.get_sheet(0).write(self.diy, 4, "用户名或密码错误")
                break
            elif self.WebDir(By.XPATH,'//*[@id="token-img"]',1):
                self.driver.maximize_window() # 窗口最大化准备截图
                self.driver.find_element_by_xpath('//*[@id="token-img"]').click()
                time.sleep(0.5)
                pngname = self.image_str('#token-img')
                if setting.identify == 0:
                    pngname = fateadm_api.TestFunc(pngname)
                else:
                    pngname = fateadm_api.baiduapi(pngname)
                self.driver.find_element_by_id("uc-common-token").send_keys(pngname)
                self.driver.find_element_by_id("submit-form").click()
            elif self.WebDir(By.XPATH,'//*[text()="拖动滑块，使图片角度为正"]',1):
                self.driver.maximize_window() # 窗口最大化准备截图
                time.sleep(0.5)
                #wx.CallAfter(self.window.LogMessase,self.user+" 准备滑块纠正")
                pngname = self.image_str('.vcode-spin-img')
                #img_url = self.driver.find_element_by_xpath('//*[@class="vcode-spin-img"]').get_attribute("src")
                getcmd = subprocess.check_output("correct_rotation.exe {}".format(pngname))
                getcmd = re.sub("[\n\r]","",getcmd.decode("gbk"))
                movex = int(int(getcmd)/360*210)
                #print(img_url)
                elenment = self.driver.find_element_by_xpath('//*[@class="vcode-spin-button"]/p')
                ActionChains(self.driver).move_to_element(elenment).perform()
                drawing = ActionChains(self.driver).click_and_hold(elenment).move_by_offset(movex, 0).release()
                drawing.perform()
            else:
                timesum +=1
        else:
            setting.worb.get_sheet(0).write(self.diy, 4, "登录失败未知原因")
        self.booksave()

    def image_str(self,idclass):
        png64 = self.driver.get_screenshot_as_base64()
        png64 = base64.b64decode(png64)
        page_snap_obj = Image.open(BytesIO(png64))
        img = self.driver.find_element_by_css_selector(idclass)
        imgxy = img.location
        right = imgxy['x'] + img.size['width']
        bottom = imgxy['y'] + img.size['height']
        image_obj = page_snap_obj.crop((imgxy['x'], imgxy['y'], right, bottom))
        if not os.path.exists("files"):
            os.mkdir("files")
        file = "files" + "\\" + str(time.time()).replace(".","") + ".png"
        image_obj.save(file)
        return file

    def booksave(self):
        try:
            setting.worb.save("百度登录.xls")
            #wx.CallAfter(self.window.LogMessase,self.user+" 保存成功")
        except PermissionError:
            logeer("表格被其他程序占用,保存失败")
            #wx.CallAfter(self.window.LogMessase,self.user+" 表格被其他程序占用,保存失败")
        except Exception as e:
            logeer(str(e))
            #wx.CallAfter(self.window.LogMessase,self.user+" 保存失败")
        self.driver.quit()

    def WebDir(self,ysu,xpath,times):
        try:
            WebDriverWait(self.driver,times).until(EC.visibility_of_element_located((ysu,xpath)))
            return True
        except:
            return False


class Chromepath():
    def __init__(self):
        path_ = os.path.join(os.path.expanduser("~"), 'Desktop')
        pythoncom.CoInitialize()
        shell = Dispatch("WScript.Shell")
        shortcut = shell.CreateShortCut(os.path.join(path_,"Google Chrome.lnk"))
        self.file_path = shortcut.Targetpath[0:-10]
        
    def reversion(self):
        versin = None
        if self.file_path:
            versin = getversion(self.file_path)
        return versin


def getversion(file_path):
    file = getpath(file_path)
    with open(file,'r') as file_:
        file_txt = file_.readlines()
    for txt in file_txt:
        if txt.replace(" ","").split("=")[0] == 'version':
            return txt.replace(" ","").split("=")[1]


def getpath(path_):
    mnet = None
    path_list = os.listdir(path_)
    for file in path_list:
        filedir = pathdir(os.path.join(path_,file))
        if filedir.is_dir():
            mnet = getpath(filedir)
            if mnet:
                return mnet
        if file[-8:] == "manifest":
            return os.path.join(path_,file)


def getpid():
    exe = None
    pid_list = psutil.pids()
    for pid in pid_list:
        try:
            exe_path = psutil.Process(pid).cmdline()[0]
            if exe_path[-10:] == "chrome.exe":
                exe = exe_path[:-11]
                break
        except:
            pass
    return exe


def getchrdir(viver):
    url = "https://npm.taobao.org/mirrors/chromedriver"
    txt = requests.get(url)
    if txt.status_code == 200:
        list_ver = re.compile(r'\d\d.\d.\d\d\d\d.\d+').findall(txt.text)
        if viver in list_ver:
            vivers = viver
        else:
            for ver in list_ver:
                if re.search("(\d+)",viver).group(0) == re.search("(\d+)",ver).group(0):
                    vivers = ver
                    break
        print(vivers)
        res = requests.get(url + "/" + vivers + "/chromedriver_win32.zip")
        if res.status_code == 200 and res.content:
            with open(vivers + "cher.zip","wb") as b:
                b.write(res.content)
            zip_file = zipfile.ZipFile(vivers + "cher.zip",mode='r',compression=zipfile.ZIP_DEFLATED)
            zip_file.extractall(vivers)
            zip_file.close()
            os.remove(vivers + "cher.zip")
            return os.path.join(os.getcwd(),vivers,"chromedriver.exe")


class MyFrame7( wx.Frame ):
    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = sys.argv[0], pos = wx.DefaultPosition, size = wx.Size( 960,540 ), style = wx.DEFAULT_FRAME_STYLE|wx.STAY_ON_TOP )
        self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )
        bSizer5 = wx.BoxSizer( wx.HORIZONTAL )
        bSizer6 = wx.BoxSizer( wx.VERTICAL )
        self.m_button9 = wx.Button( self, wx.ID_ANY, u"启动", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer6.Add( self.m_button9, 0, wx.ALL, 5 )
        self.m_textCtrl2 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer6.Add( self.m_textCtrl2, 0, wx.ALL, 5 )
        self.m_choice3 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, ["百度营销改密","百度登录"], 0 )
        self.m_choice3.SetSelection( 0 )
        bSizer6.Add( self.m_choice3, 0, wx.ALL, 5 )
        self.m_button10 = wx.Button( self, wx.ID_ANY, u"保存关闭", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer6.Add( self.m_button10, 0, wx.ALL, 5 )
        self.m_button11 = wx.Button( self, wx.ID_ANY, u"初始化", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer6.Add( self.m_button11, 0, wx.ALL, 5 )
        self.m_button12 = wx.Button( self, wx.ID_ANY, u"设置", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer6.Add( self.m_button12, 0, wx.ALL, 5 )
        bSizer5.Add( bSizer6, 1, wx.EXPAND, 5 )
        bSizer7 = wx.BoxSizer( wx.VERTICAL )
        self.m_richText1 = wx.richtext.RichTextCtrl( self, wx.ID_ANY,time.strftime("%Y-%m-%d %H:%M:%S"), wx.DefaultPosition, wx.DefaultSize, 0|wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER|wx.WANTS_CHARS )
        bSizer7.Add( self.m_richText1, 1, wx.EXPAND |wx.ALL, 5 )
        bSizer5.Add( bSizer7, 1, wx.EXPAND, 5 )
        self.SetSizer( bSizer5 )
        self.Layout()
        self.Centre( wx.BOTH )

        self.fileDrop = FileDrops(self.m_textCtrl2)
        self.m_textCtrl2.SetDropTarget(self.fileDrop)
        self.m_button11.Bind(wx.EVT_BUTTON, self.seerset)
        self.m_button12.Bind(wx.EVT_BUTTON, self.celecer)
        self.m_button9.Bind(wx.EVT_BUTTON, self.startRun)
        self.m_button10.Bind(wx.EVT_BUTTON, self.initcfg)
        self.seestar = ''
        self.m_richText1.SetStyle(0,20,wx.TextAttr("white","black"))
        self.m_richText1.SetDefaultStyle(wx.TextAttr("red","green"))
        self.Bind(wx.EVT_CLOSE, self.OnClose)

    def OnClose(self,event):
        setclass.set_cfg("db", "chromedriver", setting.chromedriver)
        setclass.set_cfg("db", "version", setting.version)
        pidlist = psutil.pids()
        for i in pidlist:
            try:
                n = psutil.Process(i)
                if n.name() == "chromedriver.exe":
                    cmd = 'taskkill /pid ' + str(i) + '  -t  -f'
                    os.popen(cmd)
            except:
                pass
        self.Destroy()

    def seerset(self,eve):
        self.m_button11.Enable(False)
        try:
            os.remove("config.ini")
        except:
            pass
        self.seestar = "初始化"	
        thre = WorkerThream(self,None)
        thre.start()

    def startRun(self,eve):
        self.m_button9.Enable(False)
        self.seestar = "run"
        if not self.m_textCtrl2.Value:
            self.m_richText1.AddParagraph(time.strftime("%Y-%m-%d %H:%M:%S") + " : " + "警告!!!账号框需要拖入文件")
            self.m_richText1.AppendText(":")
            self.m_richText1.ShowPosition(-1)
            self.m_button9.Enable(True)
            return
        wor = workbok(self,self.m_textCtrl2.Value)
        wor.start()

    def initcfg(self,eve):
        try:
            setting.work.save("百度改密.xls")
        except:
            pass
        self.Close(True)

    def celecer(self,eve):
        frame = MyFrameset(None)
        frame.Show(True)

    def LogMessase(self,cor):
        self.m_richText1.AddParagraph(time.strftime("%Y-%m-%d %H:%M:%S")+" : " + cor)
        self.m_richText1.AppendText(":")
        self.m_richText1.ShowPosition(-1)


class MyFrameset(wx.Frame):
    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = "设置界面", pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.STAY_ON_TOP)
        self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )
        bSizer5 = wx.BoxSizer( wx.VERTICAL )
        bSizer8 = wx.BoxSizer( wx.HORIZONTAL )
        m_choice5Choices = ["2","3","4","5","6","7","8","9","10","11","12"]
        self.m_choice5 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, m_choice5Choices, 0 )
        self.m_choice5.SetSelection(setting.runsum)
        bSizer8.Add( self.m_choice5, 0, wx.ALL, 5 )
        self.m_staticText4 = wx.StaticText( self, wx.ID_ANY, u"每次启动任务数量", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText4.Wrap( -1 )
        bSizer8.Add( self.m_staticText4, 0, wx.ALL, 5 )
        bSizer5.Add( bSizer8, 1, wx.EXPAND, 5 )
        bSizer9 = wx.BoxSizer( wx.HORIZONTAL )
        self.m_choice6 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, ["开","关"], 0 )
        self.m_choice6.SetSelection(setting.window)
        bSizer9.Add( self.m_choice6, 0, wx.ALL, 5 )
        self.m_staticText5 = wx.StaticText( self, wx.ID_ANY, u"浏览器界面", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText5.Wrap( -1 )
        bSizer9.Add( self.m_staticText5, 0, wx.ALL, 5 )
        bSizer5.Add( bSizer9, 1, wx.EXPAND, 5 )
        bSizer10 = wx.BoxSizer( wx.HORIZONTAL )
        self.m_choice7 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, ["单号测试","多号任务"], 0 )
        self.m_choice7.SetSelection(setting.rundef)
        bSizer10.Add( self.m_choice7, 0, wx.ALL, 5 )
        self.m_staticText6 = wx.StaticText( self, wx.ID_ANY, u"运行模式", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText6.Wrap( -1 )
        bSizer10.Add( self.m_staticText6, 0, wx.ALL, 5 )
        bSizer5.Add( bSizer10, 1, wx.EXPAND, 5 )
        bSizer12 = wx.BoxSizer( wx.HORIZONTAL )
        self.m_choice8 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, ["百度","斐斐"], 0 )
        self.m_choice8.SetSelection(setting.identify)
        bSizer12.Add( self.m_choice8, 0, wx.ALL, 5 )
        self.m_staticText7 = wx.StaticText( self, wx.ID_ANY, u"验证码识别模式", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText7.Wrap( -1 )
        bSizer12.Add( self.m_staticText7, 0, wx.ALL, 5 )
        bSizer5.Add( bSizer12, 1, wx.EXPAND, 5 )
        bSizer11 = wx.BoxSizer( wx.VERTICAL )
        self.m_button13 = wx.Button( self, wx.ID_ANY, u"确定", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer11.Add( self.m_button13, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 )
        bSizer5.Add( bSizer11, 1, wx.EXPAND, 5 )
        self.SetSizer( bSizer5 )
        self.Layout()
        self.Centre( wx.BOTH )
        self.m_button13.Bind(wx.EVT_BUTTON,self.determine)

    def determine(self,sb):
        setting.runsum = self.m_choice5.Selection
        setting.rundef = self.m_choice7.Selection
        setting.window = self.m_choice6.Selection
        setting.identify = self.m_choice8.Selection
        setclass.set_cfg("db", "runsum", setting.runsum)
        setclass.set_cfg("db", "rundef", setting.rundef)
        setclass.set_cfg("db", "window", setting.window)
        setclass.set_cfg("db", "identify", setting.identify)
        self.Close(True)


class MyFrame8 ( wx.Frame ):
    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
        self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )
        bSizer19 = wx.BoxSizer( wx.VERTICAL )
        self.m_button27 = wx.Button( self, wx.ID_ANY, u"初始化中", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer19.Add( self.m_button27, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5 )
        self.SetSizer( bSizer19 )
        self.Layout()
        self.Centre( wx.BOTH )
        self.m_button27.Bind(wx.EVT_BUTTON,self.cd)
        self.m_button27.Enable(False)
        thre = WorkerThream(self,None)
        self.seestar = "init"
        thre.start()

    def cd(self,eve):
        self.Close(True)
        frame = MyFrame7(None)
        frame.Show(True)

    def LogMessase(self,cor):
        if cor[0:6] == "驱动下载完毕":
            self.m_button27.SetLabel("初始完毕点击进入")
            self.m_button27.Enable(True)


class WorkerThream(threading.Thread):
    def __init__(self,window,sum):
        threading.Thread.__init__(self)
        self.window = window
        self.sum = sum
        self.timeToQuit = threading.Event()

    def run(self):
        if self.window.seestar == "初始化" or self.window.seestar == "init":
            vis = getwring()
            if vis:
                if vis['vis'] == True:
                    version = vis['vlaue']
                else:
                    version = getversion(vis['vlaue'])
            else:
                prath1 = r"C:\Program Files (x86)\Google\Chrome\Application"
                prath2 = r"C:\Program Files\Google\Chrome\Application"
                if os.path.exists(prath2):
                    version = getversion(prath2)
                elif os.path.exists(prath1):
                    version = getversion(prath1)
                else:
                    pidchr = getpid()
                    if pidchr:
                        wx.CallAfter(self.window.LogMessase," chrome运行中")
                        version = getversion(pidchr)
                    else:
                        wx.CallAfter(self.window.LogMessase," 您没有运行chrome")
                        chrom = Chromepath()
                        version = chrom.reversion()
            if not version:
                wx.CallAfter(self.window.LogMessase," 初始化失败,请联系管理员")
            else:
                wx.CallAfter(self.window.LogMessase," 您chrome版本为:" + version + "将为你下载对应驱动")
                setting.chromedriver = getchrdir(version.replace("\n",""))
                setting.version = version.replace("\n","")
                wx.CallAfter(self.window.LogMessase,"驱动下载完毕,初始化完成")
                if self.window.seestar == "初始化":
                    self.window.m_button11.Enable(True)

        elif self.window.seestar == "run":
            if self.window.m_choice3.Selection:
                baidu = baidulogin(self.sum["x"],self.sum["name"],self.sum["old"])
                try:
                    wx.CallAfter(self.window.LogMessase,self.sum["name"] + " 开始工作")
                    baidu.login()
                except Exception as e:
                    logeer(str(e)+" 如果有此错误记录将说明网页有所变动,需要修改程序")
                    baidu.driver.quit()
            else:
                thstrart = WorkerThread(self.window,self.sum["x"],self.sum["name"],self.sum["old"],self.sum["new"])
                try:
                    wx.CallAfter(self.window.LogMessase,self.sum["name"] + " 开始工作")
                    thstrart.login(False)
                except Exception as e:
                    logeer(str(e)+" 如果有此错误记录将说明网页有所变动,需要修改程序")
                    thstrart.driver.quit()
                    wx.CallAfter(self.window.LogMessase," 如果有此消息将说明网页有所变动")


class FileDrops(wx.FileDropTarget):
    def __init__(self,textctrl):
        wx.FileDropTarget.__init__(self)
        self.textctrl = textctrl

    def OnDropFiles(self, x, y, filePath):
        self.textctrl.Value = filePath[0]


if __name__ == "__main__":
    app = wx.App() 
    if not os.path.exists("config.ini"):
        frame = MyFrame8(None)
    else:
        frame = MyFrame7(None)
    setclass = setconfig()
    frame.Show(True)
    app.MainLoop()
	
